package com.bankcomm.luafuction;

import java.util.Timer;
import java.util.TimerTask;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaObject;
import org.keplerproject.luajava.LuaState;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.bankcomm.common.ConfigManager;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

public class LuaAccelerometer implements SensorEventListener {
    private LuaObject listener_;
    private SensorManager sensorManager_;
    private Sensor sensor_;
    public static float accelerometerX;
    public static float accelerometerY;
    public static float accelerometerZ;
    // 记录时时的状态值
//    private float xIntime_;
//    private float yIntime_;
//    private float zIntime_;
    // 数据返回给服务端的间隔时间
    private int stepTime_;
    private Timer timer_;
    private static boolean STOPACCELEROMETER = true;

    public LuaAccelerometer() {
        try {
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luaaccelerometer");
            String luahead = "accelerometer = {}; ";
            String luafc1 = "function accelerometer:setListener(listener) luaaccelerometer:setListener(listener);  end;";
            String luafc2 = "function accelerometer:startAccelerometer() luaaccelerometer:startAccelerometer();  end;";
            String luafc3 = "function accelerometer:setAccelerometerInterval (time) luaaccelerometer:setAccelerometerInterval (time);  end;";
            String luafc4 = "function accelerometer:stopAccelerometer() luaaccelerometer:stopAccelerometer();  end;";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(luafc1).concat(luafc2).concat(luafc3).concat(luafc4));
        } catch (LuaException e) {
            Utils.printException(e);
        }
    }

    public void stopAccelerometer() {
        if (null != timer_){
        	timer_.cancel();
        	timer_ = null;
        }
        if(sensorManager_ != null){
        	sensorManager_.unregisterListener(this);
        }
        sensorManager_ = null;
        sensor_ = null;
        STOPACCELEROMETER = true;
    }

    /**
     * 服务端发过来的时间以秒为单位
     * 
     * @param time
     */
    public void setAccelerometerInterval(float time) {
        stepTime_ = (int) (time * 1000);
        if (stepTime_ < 0)
            stepTime_ = 1000;
    }

    public void startAccelerometer() {
    	stopAccelerometer(); // 开始新的重力感应测量之前先取消原来的。
        // 获得传感器管理器
        sensorManager_ = (SensorManager) ConfigManager.currentView_.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager_ != null) {
            // 获得重力传感器
            sensor_ = sensorManager_.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
    }

    /**
     * 为设备重力感应设置监听方法
     * 
     * @param listener
     *            监听方法(function)
     * @return
     */
    public void setListener(final Object listener) {
        if (listener instanceof LuaObject) {
            listener_ = (LuaObject) listener;
            if (null == sensorManager_) {
                sensorManager_ = (SensorManager) ConfigManager.currentView_.getSystemService(Context.SENSOR_SERVICE);
            }
            if (null == timer_)
                timer_ = new Timer();

            timer_.schedule(new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        if (STOPACCELEROMETER) {
                            STOPACCELEROMETER = false;
                            synchronized (this) {
                                // 同步注册及坐标还原操作,否则无法取到修整得唯一坐标
                                if (null == sensor_) {
                                    sensor_ = sensorManager_.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                                } else if (sensor_ != null) {
                                    sensorManager_.registerListener(LuaAccelerometer.this, sensor_,
                                            SensorManager.SENSOR_DELAY_GAME);
                                }
                                accelerometerX = 0;
                                accelerometerY = 0;
                                accelerometerZ = 0;
                            }
                        }
                        Object[] args = new Object[1];
                        args[0] = LuaAccelerometer.this;
                        ((LuaObject) listener).call(args, 0);
                    } catch (LuaException e) {
                        // TODO Auto-generated catch block
                        Utils.printException(e);
                    }
                }
            }, 0, stepTime_);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
    	if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
    		// 获得x,y,z坐标
    		if (Component.SCREENWIDTH < Component.SCREENHEIGHT) {
    	        // 竖屏显示
    		    accelerometerX = -event.values[SensorManager.DATA_X];
    	        accelerometerY = -event.values[SensorManager.DATA_Y];
    		} else {
    		    accelerometerX = event.values[SensorManager.DATA_Y];
    	        accelerometerY = -event.values[SensorManager.DATA_X];
    		}
    		accelerometerZ = event.values[SensorManager.DATA_Z];
    	}
    }
}
